package com.quantgroup.data.saastest.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author yangjinhua
 */
@Slf4j
@Component
public class DynamicDataSource extends AbstractRoutingDataSource {

	@PostConstruct
	public void init(){
		DruidDataSource defaultDataSource = new DruidDataSource();
		defaultDataSource.setUrl("jdbc:mysql://172.29.2.5:3306/yangjinghua?useUnicode=true&characterEncoding=UTF8&autoReconnect=true&failOverReadOnly=false&useSSL=false");
		defaultDataSource.setUsername("root");
		defaultDataSource.setPassword("123456");
		defaultDataSource.setValidationQuery("select 1");
		defaultDataSource.setTestOnBorrow(true);

		Map<Object, Object> map = new HashMap<>();
		map.put("defaultDataSource",defaultDataSource);
		setTargetDataSources(map);
		setDefaultTargetDataSource(defaultDataSource);
	}


	// 保存当前线程的数据源对应的key
	private final static ThreadLocal<String> DATA_SOURCE_KEY = new ThreadLocal<>();

	// 所有数据源的key集合
	private Set<Object> keySet;

	// 切换当先线程的key
	public static void switchSource(String key) {
		DATA_SOURCE_KEY.set(key);
	}

	// 移除key值
	public static void clear() {
		DATA_SOURCE_KEY.remove();
	}

	/**
	 * AbstractRoutingDataSource抽象类实现方法，即获取当前线程数据源的key
	 * @return
	 */
	@Override
	protected Object determineCurrentLookupKey() {
		String key = DATA_SOURCE_KEY.get();
		if (!keySet.contains(key)) {
			log.info("can not found datasource by key: {},this session may use default datasource", key);
		}
		return key;
	}

	/**
	 * 配置更改后刷新keySet
	 */
	@Override
	public void afterPropertiesSet() {
		super.afterPropertiesSet();
		Map<Object, DataSource> sourceMap = super.getResolvedDataSources();
		this.keySet = sourceMap.keySet();
	}

}